package com.kuang.servlet.user;

import com.alibaba.fastjson.JSONArray;
import com.kuang.pojo.Role;
import com.kuang.pojo.User;
import com.kuang.service.UserService;
import com.kuang.service.UserServiceImpl;
import com.kuang.util.Constants;
import com.kuang.util.PageSupport;
import com.mysql.jdbc.StringUtils;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

//实现Servlet复用
public class UserServlet extends HttpServlet {

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.setCharacterEncoding("utf-8");
        resp.setCharacterEncoding("utf-8");
        resp.setHeader("content-type","text/html;charset=utf-8");
        String  method = req.getParameter("method");
        System.out.println(method);
        if(method.equals("savepwd")&&method!=null){
            this.updatePwd(req,resp);
        }else if (method.equals( "pwdmodify") && method != null) {
            this.pqdmodify(req,resp);
        }else if ("query".equals(method) && method != null) {
            System.out.println(method);
            this.userQuery(req, resp);
        }else if ("add".equals(method) && method != null) {
            this.add(req, resp);
        }else if ("getrolelist".equals(method) && method != null) {
            this.getRoleList(req, resp);
        }else if("delete".equals(method)){
            String id = req.getParameter("id");
            System.out.println("进入delete方法"+method);
            System.out.println("要删除的id为"+id);
            this.delete(req,resp);
        }else if ("modifyexe".equals(method) && method != null) {
            this.userModify(req, resp);
        }else if("update".equals(method)){
            this.update(req,resp);
        }
}

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doGet(req, resp);
    }
    //用户修改密码
    public void updatePwd(HttpServletRequest req, HttpServletResponse resp){
        //从Session里面拿Id
        Object o = req.getSession().getAttribute(Constants.User_Session);
        String newpassword = req.getParameter("newpassword");

        boolean flag = false;

        if(o!=null && !StringUtils.isNullOrEmpty(newpassword)){
            UserService userService = new UserServiceImpl();
            flag = userService.updatePwd( ( (User) o) .getId(),newpassword);
            if(flag){ //等于 flag == true
                req.setAttribute("message","修改密码成功,请退出,重新登录");
                //修改密码成功,移除当前Session
                req.getSession().removeAttribute(Constants.User_Session);
            }else {
                req.setAttribute("message","密码修改失败");
            }
        }else {
            req.setAttribute("message","新密码有问题");
        }

        try {
            req.getRequestDispatcher("pwdmodify.jsp").forward(req,resp);
        } catch (ServletException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    //旧密码验证
    public void pqdmodify(HttpServletRequest req, HttpServletResponse resp) {
        // 通过session获得用户id
        Object o = req.getSession().getAttribute(Constants.User_Session);
        String oldpassword = req.getParameter("oldpassword");

        Map<String, String> resultMap = new HashMap<String, String>();
        if(o==null) {//session失效，session过期了
            resultMap.put("result","seesionerror");
        }else if(StringUtils.isNullOrEmpty(oldpassword)){//输入密码为空
            resultMap.put("result","error");
        }else {//
            String userPassword = ((User)o).getUserPassword();//seesion中的用户密码
            if(oldpassword.equals(userPassword)) {
                resultMap.put("result","true");
            }else {
                resultMap.put("result","false");
            }
        }


        try {
            resp.setContentType("application/json");
            PrintWriter writer = resp.getWriter();
            /*
             * resultMap = ["result","sessionerror","result",error]
             * josn格式={key,value
             */
            writer.write(JSONArray.toJSONString(resultMap));
            writer.flush();
            writer.close();
        } catch (IOException e) {
            // TODO 自动生成的 catch 块
            e.printStackTrace();
        }
    }
    //获取用户列表
    private void userQuery(HttpServletRequest req, HttpServletResponse resp) {
        //查询用户列表
        String queryUserName = req.getParameter("queryname");
        String temp = req.getParameter("queryUserRole");
        String pageIndex = req.getParameter("pageIndex");
        int queryUserRole = 0;

        //获取用户列表
        UserServiceImpl userService = new UserServiceImpl();

        //第一次走这个请求，一定是第一页，页面大小固定的
        //可用把pageSize写道配置文件，方便后期修改
        int pageSize = 5;
        int currentPageNo = 1;

        if (queryUserName == null) {
            queryUserName = "";
        }
        if (temp != null && !temp.equals("")) {
            //给查询赋值 0，1，2，3，
            queryUserRole = Integer.parseInt(temp);
        }
        if (pageIndex != null) {
            currentPageNo = Integer.parseInt(pageIndex);
        }

        //获取用户数量
        int totalCount = userService.getUserCount(queryUserName, queryUserRole);
        List<User> userList = null;


        //总页数支持
        PageSupport pageSupport = new PageSupport();
        pageSupport.setCurrentPageNo(currentPageNo);
        pageSupport.setPageSize(pageSize);
        pageSupport.setTotalCount(totalCount);

        //最大页数，总共有几页【如果totalCount刚好是pageSize的整数倍，那么是不是多算了一页】
        int totalPageCount = ((int) (totalCount / pageSize)) + 1;

        //控制首页和尾页
        if (currentPageNo < 1) {
            //如果页面小于第一页，就显示第一页
            currentPageNo = 1;
        } else if (currentPageNo > totalPageCount) {
            //如果页面大于最后一页，就显示最后一页
            currentPageNo = totalPageCount;
        }

        //获取用户列表展示
        userList = userService.getUserList(queryUserName, queryUserRole, currentPageNo, pageSize);
        req.setAttribute("userList", userList);

        //获取角色列表
        List<Role> roleList = userService.getRoleList();

        req.setAttribute("roleList", roleList);
        req.setAttribute("totalCount", totalCount);
        req.setAttribute("currentPageNo", currentPageNo);
        req.setAttribute("totalPageCount", totalPageCount);
        req.setAttribute("queryUserName", queryUserName);
        req.setAttribute("queryUserRole", queryUserRole);
        //返回前端
        try {
            System.out.println("跳转");
            req.getRequestDispatcher("userlist.jsp").forward(req, resp);
            System.out.println("跳转成功");
        } catch (ServletException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    //添加用户
    private void add(HttpServletRequest req, HttpServletResponse resp) throws IOException, ServletException {
        //获取输入的用户参数
        String userCode = req.getParameter("userCode");
        String userName = req.getParameter("userName");
        String userPassword = req.getParameter("userPassword");
        String gender = req.getParameter("gender");
        String birthday = req.getParameter("birthday");
        String phone = req.getParameter("phone");
        String address = req.getParameter("address");
        String userRole = req.getParameter("userRole");

        //创建一个User对象，并且根据表单获取的内容设置其属性值
        User user = new User();
        user.setUserCode(userCode);
        user.setUserName(userName);
        user.setUserPassword(userPassword);
        user.setAddress(address);
        try {
            user.setBirthday(new SimpleDateFormat("yyyy-MM-dd").parse(birthday));
        } catch (ParseException e) {
            e.printStackTrace();
        }
        user.setGender(Integer.valueOf(gender));
        user.setPhone(phone);
        user.setUserRole(Integer.valueOf(userRole));
        user.setCreationDate(new Date());
        user.setCreatedBy(((User) req.getSession().getAttribute(Constants.User_Session)).getId());

        //调用Service层的方法
        UserService userService = new UserServiceImpl();
        if (userService.add(user)) {
            resp.sendRedirect(req.getContextPath() + "/jsp/user.do?method=query");
        } else {
            req.getRequestDispatcher("useradd.jsp").forward(req, resp);
        }
    }
    //返回用户角色列表
    private void getRoleList(HttpServletRequest req, HttpServletResponse resp) throws IOException, ServletException {
        List<Role> roleList = null;
        UserServiceImpl roleService = new UserServiceImpl();
        roleList = roleService.getRoleList();
        //把roleList转换成json对象返回
        resp.setContentType("application/json");
        PrintWriter writer = resp.getWriter();
        writer.write(JSONArray.toJSONString(roleList));
        writer.flush();
        writer.close();
    }
    //删除用户
    private void delete(HttpServletRequest req ,HttpServletResponse resp){
        String id = req.getParameter("id");
        int deleteId;
        if (id!=null){
            deleteId = Integer.parseInt(id);
            System.out.println(deleteId);
            UserServiceImpl userService = new UserServiceImpl();
            boolean flag = userService.delete(deleteId);
            if(flag) {
                try {
                    resp.sendRedirect(req.getContextPath() + "/jsp/user.do?method=query");
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }else {
                try {
                    resp.getWriter().println("网络异常,删除失败请重试");
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }else {
            try {
                resp.getWriter().println("网络异常,删除失败请重试");
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
    //修改用户
    private void userModify(HttpServletRequest req, HttpServletResponse resp) throws IOException, ServletException {
        //接收更改内容
        String id = req.getParameter("uid");
        String userName = req.getParameter("userName");
        String gender = req.getParameter("gender");
        String birthday = req.getParameter("birthday");
        String phone = req.getParameter("phone");
        String address = req.getParameter("address");
        String userRole = req.getParameter("userRole");

        //创建一个User对象，并且根据表单获取的内容设置其属性值
        User user = new User();
        user.setId(Integer.valueOf(id));
        user.setUserName(userName);
        user.setAddress(address);
        try {
            user.setBirthday(new SimpleDateFormat("yyyy-MM-dd").parse(birthday));
        } catch (ParseException e) {
            e.printStackTrace();
        }
        user.setGender(Integer.valueOf(gender));
        user.setPhone(phone);
        user.setUserRole(Integer.valueOf(userRole));
        user.setModifyBy(((User) req.getSession().getAttribute(Constants.User_Session)).getId());
        user.setModifyDate(new Date());

        UserService userService = new UserServiceImpl();
        boolean modify = userService.userModify(user);
        if (modify) {
            resp.sendRedirect(req.getContextPath() + "/jsp/user.do?method=query");
        } else {
            req.getRequestDispatcher("usermodify.jsp").forward(req, resp);
        }
    }
    //通过id获取用户信息
    private void update(HttpServletRequest req ,HttpServletResponse resp){
        System.out.println("进入update方法");
        String id = req.getParameter("id");

        int updateById = Integer.valueOf(id);
        System.out.println("updateById="+updateById + "id=" +id);
        UserServiceImpl userService = new UserServiceImpl();
        User user = userService.updateById(updateById);
        System.out.println(user.toString());
        req.setAttribute("user",user);
        try {
            req.getRequestDispatcher("usermodify.jsp").forward(req,resp);
        } catch (ServletException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}